/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.plugin.delete;

import java.awt.event.*;
import java.util.*;

import javax.swing.*;

import org.apache.commons.vfs.*;

import fileCommodore.model.*;
import fileCommodore.plugin.*;

/**
 * @author nado18@gmail.com, on Aug 7, 2007
 */
public class DeletePlugin extends Plugin
{
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see fileCommodore.plugin.Plugin#activeSelectionChanged()
	 */
	@Override
	public void activeSelectionChanged()
	{
		// TODO Auto-generated method stub
		
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see fileCommodore.plugin.Plugin#handle(java.awt.event.KeyEvent)
	 */
	@Override
	public void handle( KeyEvent ev )
	{
		if (KeyEvent.VK_F8 == ev.getKeyCode())
		{
			Vector<FileRowItem> tagged = getActiveSelection().getTagged();
			if (tagged.isEmpty())
			{
				FileRowItem item = getActiveSelection().getSelected();
				if (item != null)
				{
					int answer =
							JOptionPane.showConfirmDialog(
								getController(),
								"Are you sure you want to delete the selected file?",
								"Delete Selected File?",
								JOptionPane.OK_CANCEL_OPTION,
								JOptionPane.WARNING_MESSAGE );
					
					if (JOptionPane.OK_OPTION == answer)
					{
						try
						{
							delete( item.getFileObject() );
						}
						catch (FileSystemException e)
						{
							showError(
								"Deletion Error",
								"The selected file could not be deleted.",
								e );
						}
					}
				}
			}
			else
			{
				int answer =
						JOptionPane.showConfirmDialog(
							getController(),
							String.format(
								"Are you sure you want to delete these %d tagged files?",
								tagged.size() ),
							"Delete Tagged Files?",
							JOptionPane.OK_CANCEL_OPTION,
							JOptionPane.WARNING_MESSAGE );
				
				if (JOptionPane.OK_OPTION == answer)
				{
					StringBuffer sb = new StringBuffer();
					for (FileRowItem item : tagged)
					{
						try
						{
							delete( item.getFileObject() );
						}
						catch (FileSystemException e)
						{
							sb.append( String.format(
								"\t- %s",
								item.getFileName() ) );
						}
					}
					
					if (sb.length() > 0)
					{
						sb.insert(
							0,
							"There were errors deleting these tagged files:\r\n" );
						
						String msg = sb.toString();
						showError( "Deletion Error", msg );
					}
				}
			}
		}
	}
	
	private void delete( FileObject fo ) throws FileSystemException
	{
		fo.delete( new AllFileSelector() );
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see fileCommodore.plugin.Plugin#inactiveSelectionChanged()
	 */
	@Override
	public void inactiveSelectionChanged()
	{
		// TODO Auto-generated method stub
		
	}
	
}
